<?php

include_once('Logging.php');

class SSExpressClass
{
    const USERNAME_TEST = '';
    const APPID_TEST = 'ssebQsrN5UMSFPVNe';                                             # 商家开放平台分配的AppId
    const APPSECRET_TEST = 'dr2ZFgRysDOLAoRnDjUpEVseZfOFC492';                          # 商家标识
    const SHOPID_TEST = '20000000000000751';                                            # 商家开放平台分配的账户id

    const URL = 'https://shop.ishansong.com/seller/open/order/';                        # 下单接口地址【正式环境】 2019-11-21 闪送技术给到正式地址
//    const URL_TEST = 'https://localindev.bingex.com/seller/open/order/';                # 下单接口地址【测试环境】
    const URL_TEST = 'https://open.s.bingex.com/seller/open/order/';                # 下单接口地址【测试环境】  20200421    闪送技术给出最新地址

    private $isDebug = true;
    private $app_id = '';
    private $appsercret = '';
    private $shop_id = '';
    public function __construct($flag,$app_id,$appsercret,$shop_id)
    {
        $this->isDebug = $flag;
        $this->app_id = $app_id;
        $this->appsercret = $appsercret;
        $this->shop_id = $shop_id;

    }

    /**
     * 添加店铺
     * @param $parameter 店铺信息数组
     * @return string
     */
    public function add_shop($parameters){
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'storeSave';

        $shop_id = $this->shop_id;
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;


//        $parameters['thirdStoreId'] = '100046';                    # 第三方门店id
//        $parameters['storeName'] = '测试上海朱泾店';               # 门店名称
//        $parameters['cityName'] = '上海市';                        # 城市名称
//        $parameters['phone'] = '17321295203';                      # 联系人手机号
//        $parameters['address'] = '上海上海市金山区万安街634号(近人民路)';           # 门店地址
//        $parameters['addressDetail'] = '302';                      # 门店详细地址(楼/单元/楼层)
//        $parameters['goodType'] = 1;                               # 店铺发件类型（发件类型，1:餐饮;2:文件;3:蛋糕;4:鲜花;5:零食;6:其他;7:生鲜；8:数码；9:商超）

//        $data = array();
////        $data['address'] = $parameter['address'];
//        $data['address'] = '北京市海淀区西北旺东路10号院东区7号楼';
//        $baiduBS = new BaiduLBS();
//        $baiduBSInfo = $baiduBS::getLocation($data);
//        $baiduBSInfoArr = json_decode($baiduBSInfo, true);
//        $parameters['latitude'] = 30.903;                           # 门店纬度
//        $parameters['longitude'] = 121.173;                         # 门店经度

        $token = MD5($app_id.$shop_id.$appsercret);
        $parameters['token'] = $token;
        $parameters['clientId'] = $app_id;
        $parameters['shopId'] = $shop_id;
        $data = json_encode($parameters);
//        echo'<pre>';
//        print_r($parameters);
//        print_r($url);die;
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 获取店铺列表信息
     * @return string
     */
    public function get_shop_list(){
        $shop_id = $this->shop_id;
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'stores';
        $token = MD5($app_id.$shop_id.$appsercret);
        $post['token'] = $token;
        $post['clientId'] = $app_id;
        $post['shopId'] = $shop_id;
        $data = json_encode($post);
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
            return $info;
        }


    /**
     * 发送计费
     * 闪送
     * @return string
     */
    public function billing($parameter){
        $shop_id = $this->shop_id;
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'calculate';
        $token = MD5($app_id.$shop_id.$appsercret);
//        $parameters['storeId'] = $parameter['deliver_express_id'];                                                  # 门店编号 由添加店铺接口添加的闪送门店编号 对应后台门店需要设置
//        $parameters['thirdStoreId'] = "{$parameter['shop_no']}";                                                    # 宅配门店编号

        # 待上线前确认传哪个门店id

        $parameters['cityName'] = $parameter['deliver_city'];                                                       # 发单城市名字
        # 发件人信息
        $parameters['sender']['fromAddress'] = $parameter['shop_name'];                                             # 发件地址(来自百度地图)
        $parameters['sender']['fromAddressDetail'] = $parameter['deliver_province'].$parameter['deliver_city'].$parameter['deliver_area'].$parameter['deliver_address'];             # 发件详细地址(用户输入)
        $parameters['sender']['fromSenderName'] = $parameter['shop_name'];                                          # 发件人(长度<=30英文字符或数字)
        $parameters['sender']['fromMobile'] = $parameter['deliver_phone'];                                          # 发件人手机号
        $parameters['sender']['fromLatitude'] = $parameter['deliver_lat'];                                          # 发货人 纬度
        $parameters['sender']['fromLongitude'] = $parameter['deliver_lng'];                                         # 发货人经度
        $parameters['receiverList'][0]['orderNo'] = $parameter['shop_express_no'];                                  # 合作伙伴订单号
        $parameters['receiverList'][0]['toAddress'] = $parameter['receiver_address'];                               # 收件地址(取百度地图)
        $parameters['receiverList'][0]['toAddressDetail'] = $parameter['receiver_address'];                         # 收件详细地址(用户输入)


        $tstr = substr($parameter['shop_delivery_time'],0,strrpos($parameter['shop_delivery_time'],':'));   # 指定时间 重构   大于2小时 小于2天
        $sta = date('Y-m-d H:i:s',strtotime('+2 hour',time()));
        $end = date('Y-m-d H:i:s',strtotime('+2 day',time()));
        if($parameter['shop_delivery_time'] > $end){
            return ['status'=>400,'msg'=>'推送订单大于当前2天'];
        }
        if($parameter['shop_delivery_time']){
            if($parameter['shop_delivery_time'] > $sta ){
                $parameters['receiverList'][0]['appointType'] = 1;                                                  # 是否预约单
                $parameters['receiverList'][0]['appointmentDate'] = $tstr;                                          # 预约下单时间   闪送API 定义
            }else{
                $parameters['receiverList'][0]['appointType'] = 0;
            }
        }


        $baiduBS = new BaiduLBS();
        if($parameter['slat'] && $parameter['slng'])
            $baiduBSInfo = $baiduBS::switchLocation($parameter['slng'],$parameter['slat']); # 经 纬度
        else
            $baiduBSInfo = $baiduBS::switchLocation($parameter['lng'],$parameter['lat']);

        $location = json_decode($baiduBSInfo,true);
        $parameters['receiverList'][0]['toLongitude'] = $location['result'][0]['x'];
        $parameters['receiverList'][0]['toLatitude'] = $location['result'][0]['y'];

        $parameters['receiverList'][0]['toReceiverName'] = $parameter['receiver'];                                  # 收件人
        $parameters['receiverList'][0]['toMobile'] = $parameter['receiver_tel'];                                    # 收件人手机号,如果是隐私号此为主机号
        $parameters['receiverList'][0]['goodType'] = 6;                                                             # 发件类型（发件类型，1:餐饮;2:文件;3:蛋糕;4:鲜花;5:零食;6:其他;7:生鲜；8:数码；9:商超） 2019-11-20 暂定 6
        $parameters['receiverList'][0]['weight'] = round($parameter['actual_weight']);                              # 物品重量(公斤)
        $parameters['receiverList'][0]['remarks'] = $parameter['shop_express_remark'];                              # 备注

        $parameters['token'] = $token;
        $parameters['clientId'] = $app_id;
        $parameters['shopId'] = $shop_id;

        $datas = json_encode($parameters);

        $info = $this->http_post($url,$datas,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 确认发送订单
     * @param $parameter
     * @return string
     */
    public function send_parameter($parameter){
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;
        $shop_id = $this->shop_id;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'create';
        $token = MD5($app_id.$shop_id.$appsercret);
        $parameter['token'] = $token;
        $parameter['clientId'] = $app_id;
        $parameter['shopId'] = $shop_id;
        $data = json_encode($parameter,JSON_UNESCAPED_UNICODE);
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 加小费
     * @param $parameter
     * @return string
     */
    public function additionOrder($parameter){
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;
        $shop_id = $this->shop_id;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'additionOrder';
        $token = MD5($app_id.$shop_id.$appsercret);
        $parameter['token'] = $token;
        $parameter['clientId'] = $app_id;
        $parameter['shopId'] = $shop_id;
        $data = json_encode($parameter,JSON_UNESCAPED_UNICODE);
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 查询订单详情
     * @param $post 数组参数
     * @return string
     */
    function query($parameter){
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;
        $shop_id = $this->shop_id;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'info';
        $token = MD5($app_id.$shop_id.$appsercret);
        $parameter['token'] = $token;
        $parameter['clientId'] = $app_id;
        $parameter['shopId'] = $shop_id;
        $data = json_encode($parameter,JSON_UNESCAPED_UNICODE);
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 查询闪送员位置
     * @param $post 数组参数
     * @return string
     */
    function courier($data){
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;
        $shop_id = $this->shop_id;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'courier';
        $token = MD5($app_id.$shop_id.$appsercret);
        $parameter['token'] = $token;
        $parameter['clientId'] = $app_id;
        $parameter['shopId'] = $shop_id;
        $parameter['issOrderNo'] = $data['issOrderNo'];
        $parameter['orderNo'] = $data['orderNo'];
        $data = json_encode($parameter,JSON_UNESCAPED_UNICODE);
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }





    /**
     * 订单取消
     * @param $post 数组参数 CANCEL_TEST
     * @return string
     */
    function cancel($parameter){
        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;
        $shop_id = $this->shop_id;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'cancel';
        $token = MD5($app_id.$shop_id.$appsercret);
        $parameter['token'] = $token;
        $parameter['clientId'] = $app_id;
        $parameter['shopId'] = $shop_id;
        $data = json_encode($parameter,JSON_UNESCAPED_UNICODE);
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }

    /**
     * 查询余额
     * @param $post 数组参数 CANCEL_TEST
     * @return string
     */
    function account(){
//        $app_id = (($this->isDebug) ? self::APPID_TEST : ($this->app_id));
//        $appsercret = (($this->isDebug) ? self::APPSECRET_TEST : ($this->appsercret));
//        $shop_id = (($this->isDebug) ? self::SHOPID_TEST : ($this->shop_id));

        $app_id = $this->app_id;
        $appsercret =  $this->appsercret;
        $shop_id = $this->shop_id;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'account';
        $token = MD5($app_id.$shop_id.$appsercret);
        $parameter['token'] = $token;
        $parameter['clientId'] = $app_id;
        $parameter['shopId'] = $shop_id;
        $data = json_encode($parameter,JSON_UNESCAPED_UNICODE);
        $info = $this->http_post($url,$data,'','json','');
        if (!empty($info)){
            $info=json_decode($info, true);
        }
        return $info;
    }



    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $post_file = false, $contenttype = '', $msg = '')
    {
        $log = new Logging();
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (empty($contenttype)) {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded; charset=utf-8'));
        } else if ($contenttype == "json") {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));

        }

        $strPOST='';
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aGET = array();
            foreach ($param as $key => $val) {
                $aGET[] = $key . "=" . ($val);
            }
            $strPOST = join("&", $aGET);
        }

//        //$strPOST=http_build_query($param, '', '&');
//
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

        $time=strtotime(date('Y-m-d H:i:s'));
        $log->lfile('ss_express');
        $log->lwrite($time.','.($url));
        if (!empty($msg))$log->lwrite($time.','.$msg);
        $log->lwrite($time.','.$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);

        $log->lwrite($time.','.($sContent));

        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


}

?>